﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TweenLoopHelper : MonoBehaviour
{
    public bool UseFixedUpdate = false;
    public float duration = 1;
    public bool m_isEnable = true;


    private List<UITweener> m_list_uITweeners;
    private float time = 0;

   
    private void Awake()
    {
        m_list_uITweeners = new List<UITweener>();

        LoadTweens( this.gameObject, m_list_uITweeners);
    }

    private void FixedUpdate()
    {
        if (UseFixedUpdate) { OnUpdate(); }
    }

    private void Update()
    {
        if (!UseFixedUpdate) { OnUpdate(); }
    }

    private void OnUpdate()
    {
        if (m_isEnable)
        {
            time += Time.deltaTime;
            if (time > duration)
            {
                PlayTweens();
                time = 0;
            }
        }

    }


    void PlayTweens()
    {

        for (int i = 0, count = m_list_uITweeners.Count; i < count; i++)
        {
            m_list_uITweeners[i].ResetToBeginning();
            m_list_uITweeners[i].PlayForward();
        }
    }

    void StopTweens()
    {
        for (int i = 0, count = m_list_uITweeners.Count; i < count; i++)
        {
            m_list_uITweeners[i].enabled  = false;
            m_list_uITweeners[i].ResetToBeginning();           
        }
    }

    void LoadTweens( GameObject gTween, List<UITweener> list_uITweeners )
    {
        if (null == gTween) { return; }


        UITweener[] uITweeners = gTween.GetComponents<UITweener>();
        if (null != uITweeners && uITweeners.Length > 0) { list_uITweeners.AddRange(uITweeners); }

        for (int i = 0, count = gTween.transform.childCount; i < count; i++)
        {
            LoadTweens( gTween.transform.GetChild(i).gameObject, list_uITweeners );
        }

    }


    private void SetEnable( bool _isEnable )
    {
        m_isEnable = _isEnable;
        if (m_isEnable)
        {
            time = 0;
            PlayTweens();
        }
        else
        {
            StopTweens();
        }
      
    }

}
